require("./book.less")

var bookString = require('./book.string');
var _util = require("util/util.js");
var _product = require("service/product-service.js")
var _cart = require("service/cart-service.js")

var page = {
  init : function () {
    this.loadBookDetail();
    this.bindEvent();
  },
  loadBookDetail : function(){
    var data = {
      productId : _util.getUrlParam("id")
    }
    _product.getBookDetail(data,function(res){
      // res.images = res.detail.split(',');
      var str = "/dist/resource/subimg1.jpg";

      switch(res.categoryId){
        case 1 : {
          res.cate = "心理学入门";
          break;
        }
        case 2 : {
          res.cate = "青少年心理学";
          break;
        }
        case 3 : {
          res.cate = "应用心理学";
          break;
        }
        case 4 : {
          res.cate = "认知心理学";
          break;
        }
        case 5 : {
          res.cate = "生理心理学";
          break;
        }
        case 6 : {
          res.cate = "社会心理学";
          break;
        }
      }
      res.images = str.split(',');
      var bookHtml = _util.renderHtml(bookString,res);
      document.title = res.name;
  		$("#bookMain").html(bookHtml);
  	},function(err){
  		console.log(err);
  	})
  },
  bindEvent : function(){
    $(document).on('click','.chooseNum .fa-minus',function(){
      var num = $(".chooseNum .disabled");
      if(num.html() !== '0'){
        num.html(parseInt(num.html())-1)
        if(num.html() == '0'){
          $(this).addClass("text-dark")
        }
      }
    })
    $(document).on('click','.chooseNum .fa-plus',function(){
      var num = $(".chooseNum .disabled");
      num.html(parseInt(num.html())+1);
      if(num.html() == '1'){
        $('.chooseNum .fa-minus').removeClass('text-dark')
      }
    })
    $(document).on('scroll',function(){
      var windowH = $(window).scrollTop();
      var actionsH = parseInt($('.bookBasic').height());
      var actionsToTopH = windowH - $('.bookBasic').offset().top - actionsH;
      if(actionsToTopH > 0){
        $('.actions').addClass('fixxx')
      } else {
        $('.actions').removeClass('fixxx')
      }
    })

    //加入购物车
    $(document).on('click',"#addToCart",function(){
      var data = {
        productId : $(this).data("id"),
        count : $(".num").html()
      }
      _cart.addCart(data,function(res){
        alert("添加成功");
      },function(err){
        alert("添加失败");
      })
    })

    //立即购买
    $(document).on("click","#buyNow",function(){
      window.location.href = "./cart.html?buyNow=buyNow&id="+$(this).data("id")+"&quantity="+$(".num").html();
    })
  }
}
$(function(){
  page.init();
})